/**
 * 客户表单页面JavaScript
 * 基于Apple交互设计规范的客户信息编辑功能
 * 版本：v1.0
 * 创建时间：2025-07-20
 */

// 全局变量
let customerId = null;
let isEditMode = false;
let formData = {};
let emergencyContactIndex = 1;
let familyMemberIndex = 0;
let isDirty = false;

// DOM内容加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializePage();
    initializeEventListeners();
    initializeFormValidation();
    
    if (isEditMode) {
        loadCustomerData();
    } else {
        // 新增模式，添加默认的紧急联系人
        // 已在HTML中包含
    }
});

/**
 * 初始化页面
 */
function initializePage() {
    // 从URL获取客户ID
    const urlParams = new URLSearchParams(window.location.search);
    customerId = urlParams.get('id');
    isEditMode = !!customerId;
    
    // 更新页面标题和按钮文本
    if (isEditMode) {
        document.getElementById('page-title').textContent = '编辑客户';
        document.getElementById('main-title').textContent = '编辑客户信息';
        document.getElementById('main-subtitle').textContent = '修改客户档案信息，保持数据准确性';
        document.getElementById('submit-text').textContent = '保存修改';
        document.title = '编辑客户 - CRM旅游管理系统';
    }
    
    // 处理锚点导航
    const hash = window.location.hash;
    if (hash) {
        setTimeout(() => {
            const section = document.querySelector(hash);
            if (section) {
                section.scrollIntoView({ behavior: 'smooth' });
            }
        }, 500);
    }
}

/**
 * 初始化事件监听器
 */
function initializeEventListeners() {
    // 表单变化监听
    const form = document.getElementById('customer-form');
    if (form) {
        form.addEventListener('input', markFormDirty);
        form.addEventListener('change', markFormDirty);
    }
    
    // 出生日期变化自动计算年龄
    const birthDateInput = document.getElementById('birth-date');
    if (birthDateInput) {
        birthDateInput.addEventListener('change', calculateAge);
    }
    
    // 身份证号验证
    const idCardInput = document.getElementById('id-card');
    if (idCardInput) {
        idCardInput.addEventListener('input', validateIdCard);
        idCardInput.addEventListener('blur', extractBirthFromIdCard);
    }
    
    // 手机号验证
    document.querySelectorAll('input[type="tel"]').forEach(input => {
        input.addEventListener('input', validatePhone);
    });
    
    // 邮箱验证
    const emailInput = document.getElementById('email');
    if (emailInput) {
        emailInput.addEventListener('blur', validateEmail);
    }
    
    // 模态框事件
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('modal-overlay')) {
            closeModal(e.target.id);
        }
    });
    
    // ESC键关闭模态框
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            const openModal = document.querySelector('.modal-overlay.show');
            if (openModal) {
                closeModal(openModal.id);
            }
        }
    });
    
    // 页面离开确认
    window.addEventListener('beforeunload', function(e) {
        if (isDirty) {
            e.preventDefault();
            e.returnValue = '您有未保存的更改，确定要离开吗？';
            return e.returnValue;
        }
    });
    
    // 慢性疾病互斥选择
    const diseaseCheckboxes = document.querySelectorAll('input[name="chronic_diseases"]');
    diseaseCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', handleDiseaseSelection);
    });
    
    // 饮食限制互斥选择
    const dietCheckboxes = document.querySelectorAll('input[name="dietary_restrictions"]');
    dietCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', handleDietSelection);
    });
}

/**
 * 初始化表单验证
 */
function initializeFormValidation() {
    // 实时验证必填字段
    const requiredInputs = document.querySelectorAll('.form-group.required input, .form-group.required select');
    requiredInputs.forEach(input => {
        input.addEventListener('blur', validateRequired);
        input.addEventListener('input', clearValidationError);
    });
}

/**
 * 标记表单为已修改
 */
function markFormDirty() {
    isDirty = true;
}

/**
 * 计算年龄
 */
function calculateAge() {
    const birthDate = document.getElementById('birth-date').value;
    const ageInput = document.getElementById('calculated-age');
    
    if (birthDate && ageInput) {
        const birth = new Date(birthDate);
        const today = new Date();
        let age = today.getFullYear() - birth.getFullYear();
        const monthDiff = today.getMonth() - birth.getMonth();
        
        if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
            age--;
        }
        
        ageInput.value = `${age}岁`;
        
        // 验证年龄合理性
        if (age < 18 || age > 120) {
            showFieldError('birth-date', '请输入合理的出生日期');
        } else {
            clearFieldError('birth-date');
        }
    }
}

/**
 * 验证身份证号
 */
function validateIdCard() {
    const input = document.getElementById('id-card');
    const value = input.value.trim();
    
    if (!value) return;
    
    // 基本格式验证
    if (!/^\d{17}[\dXx]$/.test(value)) {
        showFieldError('id-card', '请输入正确的18位身份证号');
        return;
    }
    
    // 校验位验证
    const factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    const checkCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
    
    let sum = 0;
    for (let i = 0; i < 17; i++) {
        sum += parseInt(value[i]) * factors[i];
    }
    
    const checkCode = checkCodes[sum % 11];
    if (value[17].toUpperCase() !== checkCode) {
        showFieldError('id-card', '身份证号校验位错误');
        return;
    }
    
    clearFieldError('id-card');
}

/**
 * 从身份证号提取出生日期
 */
function extractBirthFromIdCard() {
    const idCard = document.getElementById('id-card').value.trim();
    const birthDateInput = document.getElementById('birth-date');
    
    if (idCard.length === 18 && /^\d{17}[\dXx]$/.test(idCard)) {
        const birthStr = idCard.substring(6, 14);
        const year = birthStr.substring(0, 4);
        const month = birthStr.substring(4, 6);
        const day = birthStr.substring(6, 8);
        
        const birthDate = `${year}-${month}-${day}`;
        
        // 验证日期有效性
        const date = new Date(birthDate);
        if (date instanceof Date && !isNaN(date)) {
            birthDateInput.value = birthDate;
            calculateAge();
        }
    }
}

/**
 * 验证手机号
 */
function validatePhone(e) {
    const input = e.target;
    const value = input.value.trim();
    
    if (!value) return;
    
    if (!/^1[3-9]\d{9}$/.test(value)) {
        showFieldError(input.id, '请输入正确的11位手机号');
    } else {
        clearFieldError(input.id);
    }
}

/**
 * 验证邮箱
 */
function validateEmail() {
    const input = document.getElementById('email');
    const value = input.value.trim();
    
    if (!value) return;
    
    if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(value)) {
        showFieldError('email', '请输入正确的邮箱地址');
    } else {
        clearFieldError('email');
    }
}

/**
 * 验证必填字段
 */
function validateRequired(e) {
    const input = e.target;
    const value = input.value.trim();
    
    if (!value) {
        showFieldError(input.id, '此字段为必填项');
    } else {
        clearFieldError(input.id);
    }
}

/**
 * 清除验证错误
 */
function clearValidationError(e) {
    clearFieldError(e.target.id);
}

/**
 * 显示字段错误
 */
function showFieldError(fieldId, message) {
    const input = document.getElementById(fieldId);
    if (!input) return;
    
    const formGroup = input.closest('.form-group');
    if (!formGroup) return;
    
    // 添加错误样式
    formGroup.classList.add('error');
    
    // 移除已存在的错误信息
    const existingError = formGroup.querySelector('.form-error');
    if (existingError) {
        existingError.remove();
    }
    
    // 添加错误信息
    const errorEl = document.createElement('div');
    errorEl.className = 'form-error';
    errorEl.innerHTML = `<i class="fas fa-exclamation-circle"></i> ${message}`;
    
    // 插入错误信息
    const helpText = formGroup.querySelector('.form-help');
    if (helpText) {
        formGroup.insertBefore(errorEl, helpText.nextSibling);
    } else {
        formGroup.appendChild(errorEl);
    }
}

/**
 * 清除字段错误
 */
function clearFieldError(fieldId) {
    const input = document.getElementById(fieldId);
    if (!input) return;
    
    const formGroup = input.closest('.form-group');
    if (!formGroup) return;
    
    formGroup.classList.remove('error');
    const errorEl = formGroup.querySelector('.form-error');
    if (errorEl) {
        errorEl.remove();
    }
}

/**
 * 处理慢性疾病选择
 */
function handleDiseaseSelection(e) {
    const noneOption = document.querySelector('input[name="chronic_diseases"][value="无"]');
    const otherOptions = document.querySelectorAll('input[name="chronic_diseases"]:not([value="无"])');
    
    if (e.target.value === '无') {
        if (e.target.checked) {
            // 选择"无"时，取消其他选项
            otherOptions.forEach(option => {
                option.checked = false;
            });
        }
    } else {
        if (e.target.checked && noneOption) {
            // 选择其他疾病时，取消"无"选项
            noneOption.checked = false;
        }
    }
}

/**
 * 处理饮食限制选择
 */
function handleDietSelection(e) {
    const noneOption = document.querySelector('input[name="dietary_restrictions"][value="无特殊要求"]');
    const otherOptions = document.querySelectorAll('input[name="dietary_restrictions"]:not([value="无特殊要求"])');
    
    if (e.target.value === '无特殊要求') {
        if (e.target.checked) {
            // 选择"无特殊要求"时，取消其他选项
            otherOptions.forEach(option => {
                option.checked = false;
            });
        }
    } else {
        if (e.target.checked && noneOption) {
            // 选择其他限制时，取消"无特殊要求"选项
            noneOption.checked = false;
        }
    }
}

/**
 * 添加紧急联系人
 */
function addEmergencyContact() {
    const container = document.querySelector('.emergency-contacts-container');
    if (!container) return;
    
    const contactItem = document.createElement('div');
    contactItem.className = 'emergency-contact-item';
    contactItem.setAttribute('data-index', emergencyContactIndex);
    
    contactItem.innerHTML = `
        <div class="contact-header">
            <h3 class="contact-title">联系人 #${emergencyContactIndex + 1}</h3>
            <div class="contact-actions">
                <label class="primary-contact-toggle">
                    <input type="radio" name="primary_contact" value="${emergencyContactIndex}">
                    <span class="toggle-label">主要联系人</span>
                </label>
                <button type="button" class="remove-contact-btn" onclick="removeEmergencyContact(${emergencyContactIndex})">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        </div>
        <div class="form-grid">
            <div class="form-group required">
                <label class="form-label">
                    联系人姓名
                    <span class="required-mark">*</span>
                </label>
                <input type="text" name="emergency_contacts[${emergencyContactIndex}][name]" class="form-input" 
                       placeholder="请输入联系人姓名" required maxlength="50">
            </div>
            <div class="form-group required">
                <label class="form-label">
                    关系
                    <span class="required-mark">*</span>
                </label>
                <select name="emergency_contacts[${emergencyContactIndex}][relationship]" class="form-select" required>
                    <option value="">请选择关系</option>
                    <option value="配偶">配偶</option>
                    <option value="子女">子女</option>
                    <option value="亲属">亲属</option>
                    <option value="朋友">朋友</option>
                    <option value="其他">其他</option>
                </select>
            </div>
            <div class="form-group required">
                <label class="form-label">
                    联系电话
                    <span class="required-mark">*</span>
                </label>
                <input type="tel" name="emergency_contacts[${emergencyContactIndex}][phone]" class="form-input" 
                       placeholder="请输入11位手机号" required maxlength="11">
            </div>
        </div>
    `;
    
    container.appendChild(contactItem);
    emergencyContactIndex++;
    markFormDirty();
    
    // 为新添加的手机号输入框添加验证
    const phoneInput = contactItem.querySelector('input[type="tel"]');
    if (phoneInput) {
        phoneInput.addEventListener('input', validatePhone);
    }
}

/**
 * 移除紧急联系人
 */
function removeEmergencyContact(index) {
    const contactItem = document.querySelector(`[data-index="${index}"]`);
    if (contactItem) {
        contactItem.remove();
        markFormDirty();
        
        // 重新编号剩余联系人
        renumberEmergencyContacts();
    }
}

/**
 * 重新编号紧急联系人
 */
function renumberEmergencyContacts() {
    const contacts = document.querySelectorAll('.emergency-contact-item');
    contacts.forEach((contact, index) => {
        const title = contact.querySelector('.contact-title');
        if (title) {
            title.textContent = `联系人 #${index + 1}`;
        }
    });
}

/**
 * 添加家庭成员
 */
function addFamilyMember() {
    const container = document.querySelector('.family-members-container');
    if (!container) return;
    
    const memberItem = document.createElement('div');
    memberItem.className = 'family-member-item';
    memberItem.setAttribute('data-index', familyMemberIndex);
    
    memberItem.innerHTML = `
        <div class="member-header">
            <h4 class="member-title">家庭成员 #${familyMemberIndex + 1}</h4>
            <button type="button" class="remove-member-btn" onclick="removeFamilyMember(${familyMemberIndex})">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div class="form-grid">
            <div class="form-group required">
                <label class="form-label">
                    成员类型
                    <span class="required-mark">*</span>
                </label>
                <select name="family_members[${familyMemberIndex}][type]" class="form-select" required>
                    <option value="">请选择成员类型</option>
                    <option value="配偶">配偶</option>
                    <option value="子女">子女</option>
                    <option value="其他亲属">其他亲属</option>
                </select>
            </div>
            <div class="form-group required">
                <label class="form-label">
                    成员姓名
                    <span class="required-mark">*</span>
                </label>
                <input type="text" name="family_members[${familyMemberIndex}][name]" class="form-input" 
                       placeholder="请输入成员姓名" required maxlength="50">
            </div>
            <div class="form-group">
                <label class="form-label">联系电话</label>
                <input type="tel" name="family_members[${familyMemberIndex}][phone]" class="form-input" 
                       placeholder="请输入手机号" maxlength="11">
            </div>
            <div class="form-group">
                <label class="form-label">年龄</label>
                <input type="number" name="family_members[${familyMemberIndex}][age]" class="form-input" 
                       placeholder="请输入年龄" min="0" max="150">
            </div>
            <div class="form-group">
                <label class="form-label">关系亲密度</label>
                <select name="family_members[${familyMemberIndex}][closeness]" class="form-select">
                    <option value="关系密切" selected>关系密切</option>
                    <option value="关系一般">关系一般</option>
                    <option value="关系疏远">关系疏远</option>
                </select>
            </div>
            <div class="form-group">
                <label class="form-label">对旅游的态度</label>
                <select name="family_members[${familyMemberIndex}][travel_attitude]" class="form-select">
                    <option value="支持" selected>支持</option>
                    <option value="中立">中立</option>
                    <option value="反对">反对</option>
                </select>
            </div>
        </div>
    `;
    
    container.appendChild(memberItem);
    familyMemberIndex++;
    markFormDirty();
    
    // 为新添加的手机号输入框添加验证
    const phoneInput = memberItem.querySelector('input[type="tel"]');
    if (phoneInput) {
        phoneInput.addEventListener('input', validatePhone);
    }
}

/**
 * 移除家庭成员
 */
function removeFamilyMember(index) {
    const memberItem = document.querySelector(`.family-member-item[data-index="${index}"]`);
    if (memberItem) {
        memberItem.remove();
        markFormDirty();
        
        // 重新编号剩余成员
        renumberFamilyMembers();
    }
}

/**
 * 重新编号家庭成员
 */
function renumberFamilyMembers() {
    const members = document.querySelectorAll('.family-member-item');
    members.forEach((member, index) => {
        const title = member.querySelector('.member-title');
        if (title) {
            title.textContent = `家庭成员 #${index + 1}`;
        }
    });
}

/**
 * 加载客户数据
 */
function loadCustomerData() {
    if (!customerId) return;
    
    showLoading();
    
    // 模拟API调用
    setTimeout(() => {
        const customerData = generateMockCustomerData();
        populateForm(customerData);
        hideLoading();
    }, 800);
}

/**
 * 生成模拟客户数据
 */
function generateMockCustomerData() {
    return {
        name: '张大爷',
        gender: '男',
        birth_date: '1955-03-15',
        id_card: '110101195503151234',
        work_status: '退休',
        occupation: '退休教师',
        status: '有效客户',
        primary_phone: '13800138001',
        backup_phone: '13900138888',
        wechat: 'zhangdaye1955',
        email: 'zhangdaye@example.com',
        address: '北京市朝阳区某某街道某某小区8号楼3单元502室',
        postal_code: '100020',
        preferred_contact_method: '电话',
        referrer_name: '王老师',
        referrer_phone: '13600137788',
        referrer_relation: '朋友推荐',
        referrer_date: '2025-01-10',
        tags: ['VIP客户', '身体健康', '易沟通']
    };
}

/**
 * 填充表单数据
 */
function populateForm(data) {
    Object.keys(data).forEach(key => {
        const element = document.querySelector(`[name="${key}"]`);
        if (element) {
            if (element.type === 'radio') {
                const radio = document.querySelector(`[name="${key}"][value="${data[key]}"]`);
                if (radio) radio.checked = true;
            } else if (element.type === 'checkbox') {
                if (Array.isArray(data[key])) {
                    data[key].forEach(value => {
                        const checkbox = document.querySelector(`[name="${key}"][value="${value}"]`);
                        if (checkbox) checkbox.checked = true;
                    });
                }
            } else {
                element.value = data[key];
            }
        }
    });
    
    // 计算年龄
    calculateAge();
    
    // 标记表单为未修改
    isDirty = false;
}

/**
 * 返回上一页
 */
function goBack() {
    if (isDirty) {
        if (confirm('您有未保存的更改，确定要离开吗？')) {
            window.history.back();
        }
    } else {
        window.history.back();
    }
}

/**
 * 重置表单
 */
function resetForm() {
    if (confirm('确定要重置表单吗？所有未保存的修改将丢失。')) {
        const form = document.getElementById('customer-form');
        if (form) {
            form.reset();
            
            // 清除所有验证错误
            document.querySelectorAll('.form-group.error').forEach(group => {
                group.classList.remove('error');
            });
            document.querySelectorAll('.form-error').forEach(error => {
                error.remove();
            });
            
            // 重新加载数据（编辑模式）
            if (isEditMode) {
                loadCustomerData();
            }
            
            isDirty = false;
        }
    }
}

/**
 * 保存为草稿
 */
function saveAsDraft() {
    const formData = collectFormData();
    
    showLoading();
    
    // 模拟API调用
    setTimeout(() => {
        hideLoading();
        showAlert('草稿保存成功', 'success');
        isDirty = false;
    }, 1000);
}

/**
 * 提交表单
 */
function submitForm() {
    // 验证表单
    if (!validateForm()) {
        showAlert('请检查并修正表单中的错误', 'error');
        return;
    }
    
    // 显示保存确认模态框
    const modal = document.getElementById('save-confirm-modal');
    if (modal) {
        modal.classList.add('show');
    }
}

/**
 * 确认保存
 */
function confirmSave() {
    const saveType = document.querySelector('input[name="save-type"]:checked')?.value || 'final';
    const formData = collectFormData();
    
    closeModal('save-confirm-modal');
    showLoading();
    
    // 模拟API调用
    setTimeout(() => {
        hideLoading();
        
        if (saveType === 'draft') {
            showAlert('草稿保存成功', 'success');
            isDirty = false;
        } else {
            const action = isEditMode ? '修改' : '创建';
            showAlert(`客户${action}成功`, 'success');
            
            setTimeout(() => {
                if (isEditMode) {
                    window.location.href = `customer-detail.html?id=${customerId}`;
                } else {
                    window.location.href = 'customer-list.html';
                }
            }, 1500);
        }
    }, 1500);
}

/**
 * 验证表单
 */
function validateForm() {
    let isValid = true;
    
    // 验证必填字段
    const requiredFields = document.querySelectorAll('.form-group.required input, .form-group.required select');
    requiredFields.forEach(field => {
        if (!field.value.trim()) {
            showFieldError(field.id || field.name, '此字段为必填项');
            isValid = false;
        }
    });
    
    // 验证手机号格式
    document.querySelectorAll('input[type="tel"]').forEach(input => {
        if (input.value.trim() && !/^1[3-9]\d{9}$/.test(input.value.trim())) {
            showFieldError(input.id, '请输入正确的11位手机号');
            isValid = false;
        }
    });
    
    // 验证邮箱格式
    const email = document.getElementById('email').value.trim();
    if (email && !/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email)) {
        showFieldError('email', '请输入正确的邮箱地址');
        isValid = false;
    }
    
    // 验证身份证号
    const idCard = document.getElementById('id-card').value.trim();
    if (idCard && !/^\d{17}[\dXx]$/.test(idCard)) {
        showFieldError('id-card', '请输入正确的18位身份证号');
        isValid = false;
    }
    
    return isValid;
}

/**
 * 收集表单数据
 */
function collectFormData() {
    const form = document.getElementById('customer-form');
    const formData = new FormData(form);
    const data = {};
    
    // 处理普通字段
    for (let [key, value] of formData.entries()) {
        if (data[key]) {
            // 处理复选框等多值字段
            if (Array.isArray(data[key])) {
                data[key].push(value);
            } else {
                data[key] = [data[key], value];
            }
        } else {
            data[key] = value;
        }
    }
    
    // 处理复选框
    const checkboxGroups = ['consumption_characteristics', 'domestic_preferences', 'international_preferences', 'chronic_diseases', 'dietary_restrictions', 'influence_factors', 'tags'];
    checkboxGroups.forEach(group => {
        const checkboxes = document.querySelectorAll(`input[name="${group}"]:checked`);
        data[group] = Array.from(checkboxes).map(cb => cb.value);
    });
    
    return data;
}

/**
 * 关闭模态框
 */
function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.remove('show');
    }
}

/**
 * 显示加载状态
 */
function showLoading() {
    const form = document.getElementById('customer-form');
    if (form) {
        form.classList.add('form-loading');
    }
}

/**
 * 隐藏加载状态
 */
function hideLoading() {
    const form = document.getElementById('customer-form');
    if (form) {
        form.classList.remove('form-loading');
    }
}

/**
 * 显示提示信息
 */
function showAlert(message, type = 'info') {
    // 创建提示元素
    const alert = document.createElement('div');
    alert.className = `alert alert-${type}`;
    alert.style.cssText = `
        position: fixed;
        top: 80px;
        right: 20px;
        z-index: 9999;
        opacity: 0;
        transform: translateY(-20px);
        transition: all 0.3s ease;
        max-width: 300px;
        padding: 12px 16px;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        display: flex;
        align-items: center;
        gap: 8px;
    `;
    
    // 根据类型设置样式
    const styles = {
        info: { bg: 'rgba(0, 122, 255, 0.1)', color: '#007AFF', icon: 'fa-info-circle' },
        success: { bg: 'rgba(52, 199, 89, 0.1)', color: '#34C759', icon: 'fa-check-circle' },
        warning: { bg: 'rgba(255, 149, 0, 0.1)', color: '#FF9500', icon: 'fa-exclamation-triangle' },
        error: { bg: 'rgba(255, 59, 48, 0.1)', color: '#FF3B30', icon: 'fa-times-circle' }
    };
    
    const style = styles[type] || styles.info;
    alert.style.backgroundColor = style.bg;
    alert.style.color = style.color;
    alert.style.border = `1px solid ${style.color}25`;
    
    alert.innerHTML = `
        <i class="fas ${style.icon}" style="flex-shrink: 0;"></i>
        <span style="font-size: 14px;">${message}</span>
    `;
    
    // 添加到页面
    document.body.appendChild(alert);
    
    // 显示动画
    setTimeout(() => {
        alert.style.opacity = '1';
        alert.style.transform = 'translateY(0)';
    }, 10);
    
    // 自动移除
    setTimeout(() => {
        alert.style.opacity = '0';
        alert.style.transform = 'translateY(-20px)';
        setTimeout(() => {
            if (document.body.contains(alert)) {
                document.body.removeChild(alert);
            }
        }, 300);
    }, 3000);
}